<?php

namespace IDock\Common\Tools;

class SoapXml
{
    public static function ArrayToXml($arr,$service,$root='request',$function='new')
    {
        $tag = 'xmlns:'.$function.'="http://newWS.front.app.echannel.ebiz.alltrust.com/"';
        $xml = self::ToXML($arr,$root);
        return '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" '.$tag.'><soapenv:Header/><soapenv:Body><'.$service.'>'.$xml.'</'.$service.'></soapenv:Body></soapenv:Envelope>';
    }

    private static function ToXML($array, $root,$label='')
    {
        $xml = '';

        foreach ($array as $key => $val){
            if(is_array($val)){
                if (!isset($val[0])) {
                    if (is_int($key)) {
                        $xml .= "<" . $label . ">" . self::ToXML($val, '', '') . "</" . $label . ">";
                    } else {
                        $xml .= "<" . $key . ">" . self::ToXML($val, '', '') . "</" . $key . ">";
                    }
                } else {
                    $xml .= self::ToXML($val, '',  $key);
                }
            }else{
                if(is_int($key)){
                    $xml .= "<" . $label . ">" . $val . "</" . $label . ">";
                }else{
                    $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
                }

            }

        }
        if($root){
            $xml = "<$root>".$xml."</$root>";
        }
        return $xml;

    }
}
